package com.xuzhiguang.baidu.pan.sdk.common.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author xuzhiguang
 * @date 2020/6/25 20:58
 */
public class HttpUtil {

    /**
     * 将请求数据转换为url segment
     * @param parameters
     * @return
     */
    public static String parametersToString(Map<String, String> parameters) {

        StringBuilder parametersStr = new StringBuilder();
        boolean first = true;

        for (Map.Entry<String, String> p : parameters.entrySet()) {
            String key = p.getKey();
            String value = String.valueOf(p.getValue());

            if (!first) {
                parametersStr.append("&");
            } else {
                first = false;
            }

            try {
                parametersStr.append(URLEncoder.encode(key, HttpConstant.DEFAULT_CHARSET));
                if (value != null) {
                    parametersStr.append("=").append(URLEncoder.encode(value, HttpConstant.DEFAULT_CHARSET));
                }
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException("url parameter encoder fail", e);
            }

        }

        return parametersStr.toString();
    }
}
